package com.net.io.netty.stickhalfpk.resolve.length;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;

import java.net.InetSocketAddress;

/**
 * @author zhangtengfei
 * @date 2022/2/15 17:37
 */
public class FixedLengthEchoClient {

    public final static String REQUEST = "Mark,Lison,Peter,James,Deer";

    private final String host;

    public FixedLengthEchoClient(String host) {
        this.host = host;
    }

    public void start() throws InterruptedException {
        // 线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //客户端启动必须
            final Bootstrap b = new Bootstrap();
            // 将线程组传入
            b.group(group)
                    // 指定使用NIO进行网络传输
                    .channel(NioSocketChannel.class)
                    // 配置要连接服务器的ip地址和端口
                    .remoteAddress(new InetSocketAddress(host, FixedLengthEchoServer.PORT))
                    .handler(new ChannelInitializerImp());
            ChannelFuture f = b.connect().sync();
            System.out.println("已连接到服务器.....");
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    private static class ChannelInitializerImp extends ChannelInitializer<Channel> {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            // TODO: 2022/2/15 采用固定长度（server端字符串长度）
            System.out.println(FixedLengthEchoServer.RESPONSE.length());
            ch.pipeline().addLast(new FixedLengthFrameDecoder(FixedLengthEchoServer.RESPONSE.length()));
            ch.pipeline().addLast(new FixedLengthClientHandler());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new FixedLengthEchoClient("127.0.0.1").start();
    }
}
